/*
* SMILParser
*
* Version 1.0
*
* Programmers: Jesse Louderback, Noah Pham, Chad Carpenter, and Marc Hindman
*/
package com.SmilDial;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.session.AccessTokenPair;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.Session.AccessType;

import CloudPackage.Cloud;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.*;

public class SmilDialActivity extends Activity {
	Button btnCompose;
	Button btnSend;
	final static private String APP_KEY = "q5jy9mbkmc13m7y";
	final static private String APP_SECRET = "r5614rxo1s9fj44";
	final static private AccessType ACCESS_TYPE = AccessType.DROPBOX;
	public static DropboxAPI<AndroidAuthSession> mDBApi;
	public static Cloud smilDialCloud = new Cloud();
	final static private String ACCOUNT_PREFS_NAME = "prefs";
	final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
	final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
	final String fileName = "dboxConfig";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		startService(new Intent(this, comm.SMS_Service.class));
		setContentView(R.layout.main);
		
		if (!getToken()) {
			AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
			AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
			mDBApi = new DropboxAPI<AndroidAuthSession>(session);
			mDBApi.getSession().startAuthentication(SmilDialActivity.this);
		}

		btnCompose = (Button) findViewById(R.id.btnCompose);
		btnSend = (Button) findViewById(R.id.btnInbox);

		btnCompose.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(SmilDialActivity.this,
										   TextMenu.class);
				startActivity(intent);
			}
		});

		btnSend.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(SmilDialActivity.this,
										   InboxMenu.class);
				startActivity(intent);
			}
		});
	}

	private boolean getToken() {
		try {
			String[] Keys = new String[2];
			File sdCard = Environment.getExternalStorageDirectory();
			File dir = new File(sdCard.getAbsolutePath() + "/SMIL Messages");
			
			// Open the file that is the first command line parameter
			FileInputStream fstream = new FileInputStream(dir + "/" + fileName);
			
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			
			// Read File Line By Line
			while ((strLine = br.readLine()) != null) {
				String[] holder;
				holder = strLine.split(":");
				if (holder[0].equals("AccTokKey")) {
					Keys[0] = holder[1];
				} else if (holder[0].equals("AccTokSec")) {
					Keys[1] = holder[1];
				}
			}
			AccessTokenPair appTokens = new AccessTokenPair(Keys[0], Keys[1]);
			AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
			AndroidAuthSession session = new AndroidAuthSession(appKeys,
					ACCESS_TYPE, appTokens);
			mDBApi = new DropboxAPI<AndroidAuthSession>(session);
			// Close the input stream
			in.close();
			return mDBApi.getSession().authenticationSuccessful();
		} catch (Exception e) {
			System.err.println("Error: " + e.getMessage());
		}

		return false;
	}

	// This functions makes the variable mDBApi global
	public static synchronized DropboxAPI<AndroidAuthSession> getInstance() {
		return mDBApi;
	}

	// This functions makes the variable smilDialCloud global
	public static synchronized Cloud getCloudInstance() {
		return smilDialCloud;
	}

	protected void onResume() {
		super.onResume();

		if (mDBApi.getSession().authenticationSuccessful()) {
			try {
				
				/* MANDATORY call to complete auth.  Sets the access token 
				 * on the session
				 */
				mDBApi.getSession().finishAuthentication();

				AccessTokenPair tokens = mDBApi.getSession()
						.getAccessTokenPair();

				/* 
				 * Provide your own storeKeys to persist the access token pair
				 * A typical way to store tokens is using SharedPreferences
				 */
				storeKeys(tokens.key, tokens.secret);
				saveToken();
			} catch (IllegalStateException e) {
				Log.i("DbAuthLog", "Error authenticating", e);
			}
		}
	}

	public String[] getKeys() {
		SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
		String key = prefs.getString(ACCESS_KEY_NAME, null);
		String secret = prefs.getString(ACCESS_SECRET_NAME, null);
		if (key != null && secret != null) {
			String[] ret = new String[2];
			ret[0] = key;
			ret[1] = secret;
			return ret;
		} else {
			return null;
		}
	}

	/**
	 * Shows keeping the access keys returned from Trusted Authenticator in a
	 * local store, rather than storing user name & password, and
	 * re-authenticating each time (which is not to be done, ever).
	 */
	public void storeKeys(String key, String secret) {
		
		// Save the access key for later
		SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
		Editor edit = prefs.edit();
		edit.putString(ACCESS_KEY_NAME, key);
		edit.putString(ACCESS_SECRET_NAME, secret);
		edit.commit();
	}

	public void clearKeys() {
		SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
		Editor edit = prefs.edit();
		edit.clear();
		edit.commit();
	}

	public void saveToken() {
		File sdCard = Environment.getExternalStorageDirectory();

		FileWriter fos;
		try {
			File dir = new File(sdCard.getAbsolutePath() + "/SMIL Messages");
			dir.mkdirs();
			File file = new File(dir, fileName);

			fos = new FileWriter(file, false);
			fos.write("AccTokSec:"
					+ mDBApi.getSession().getAccessTokenPair().secret
					+ "\nAccTokKey:"
					+ mDBApi.getSession().getAccessTokenPair().key);
			
			// fos.write(str.getBytes());
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}